package com.mtw.bbs.bbsUser.controller.provider;

import cn.hutool.core.util.DesensitizedUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mtw.bbs.bbsUser.pojo.entity.ResourceAPI;
import com.mtw.bbs.bbsUser.pojo.entity.User;
import com.mtw.bbs.bbsUser.pojo.vo.UserVo;
import com.mtw.bbs.bbsUser.service.ResourceAPIService;
import com.mtw.bbs.bbsUser.service.UserFollowService;
import com.mtw.bbs.bbsUser.service.UserService;
import com.mtw.bbs.bbsUser.utils.AvatarUtilz;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.userAdmin.pojo.dto.UserDto;
import com.mtw.bbs.userAdmin.pojo.vo.UserInfoVo;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;



@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("provide/user")
public class UserProvider {


    private final AvatarUtilz avatarUtilz;
    private final UserService userService;
    private final UserFollowService userFollowService;
    private final ResourceAPIService resourceAPIService;



    /**
     * 根据username获取用户信息
     */
    @ApiOperation(value = "获取用户信息", notes = "传入用户username")
    @GetMapping("/getUserVoByUsername")
    public Result<UserVo> getUserVoByUsername(@RequestParam("username") String username) {
        User user = userService.getUserInfoByUsername(username);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(user, vo);
        if (StringUtils.isNotBlank(user.getPhone())){
            vo.setPhone(DesensitizedUtil.mobilePhone(user.getPhone()));
        }
        avatarUtilz.setAvatarUrl(vo);
        UserDetails currentUser = SecurityContextHolder.getContext().getAuthentication();
        // 不是查当前用户数据时，查当前用户是否关注了被查询的用户
        if (currentUser != null && !user.getId().equals(currentUser.getId())){
            vo.setFollowed(userFollowService.getIsFollowed(currentUser.getId(),user.getId()));
        }
        return Result.success(vo);
    }




    /**
     * 根据username获取用户信息
     */
    @ApiOperation(value = "获取用户信息", notes = "传入用户username")
    @GetMapping("/getUserInfoByUsername")
    public Result<UserDto> getUserInfoByUsername(@RequestParam("username") String username) {
        User user = userService.getUserInfoByUsername(username);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        UserDto dto = new UserDto();
        BeanUtils.copyProperties(user, dto);
        avatarUtilz.setAvatarUrl(dto);
        return Result.success(dto);
    }


    /**
     * 根据id获取用户信息
     */
    @ApiOperation(value = "获取用户信息", notes = "传入用户id")
    @GetMapping("/getUserInfoById")
    public Result<UserDto> getUserinfoById(@RequestParam("userId") String userId) {
        User user = userService.getUserInfoById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        UserDto dto = new UserDto();
        BeanUtils.copyProperties(user, dto);
        avatarUtilz.setAvatarUrl(dto);
        return Result.success(dto);
    }


    /**
     * 根据id集合获取用户信息
     */
    @ApiOperation(value = "获取用户信息", notes = "传入用户id")
    @PostMapping("/getUserInfoByIds")
    public Result getUserInfoByIds(@RequestBody String[] userIds) {
        List<User> userList = userService.getUserInfoByIds(Arrays.asList(userIds));
        if (userList == null) {
            return Result.fail("用户不存在");
        }

        List<UserDto> dtos = userList.stream().map(x -> {
            UserDto dto = new UserDto();
            BeanUtils.copyProperties(x, dto);
            return dto;
        }).collect(Collectors.toList());
        avatarUtilz.setAvatarUrls(dtos);
        return Result.success(dtos);
    }


    /**
     * 加载用户信息
     */
    @ApiOperation(value = "根据用户名或手机号及密码获取用户", notes = "传入用户username或手机号，密码必填")
    @GetMapping("/loadUserByPassword")
    public Result<UserDto> loadUserByPassword(@RequestParam(name = "username") String username,
                                              @RequestParam(name = "password") String password) {


        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPassword,password);
        lqw.and(oqw->oqw.eq(User::getUsername,username).or().eq(User::getPhone,username));
        User user = userService.getOne(lqw);
        if (user == null) {
            return Result.fail("用户不存在或密码错误！");
        }
        UserDto dto = new UserDto();
        BeanUtils.copyProperties(user, dto);
        dto.setResource(resourceAPIService.queryResourceByUserId(dto.getId()).stream().map(ResourceAPI::toVo).collect(Collectors.toSet()));
        return Result.success(dto);
    }


    /**
     * 根据username加载用户信息
     */
    @ApiOperation(value = "根据用户名获取用户", notes = "传入用户username")
    @GetMapping("/loadUser")
    public Result<UserDto> loadUserByUserName(@RequestParam("username") String username) {

        User user = userService.loadUserByUserName(username);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        UserDto dto = new UserDto();
        BeanUtils.copyProperties(user, dto);
        dto.setResource(resourceAPIService.queryResourceByUserId(dto.getId()).stream().map(ResourceAPI::toVo).collect(Collectors.toSet()));
        return Result.success(dto);
    }


    /**
     * 根据mobile加载用户信息
     */
    @ApiOperation(value = "根据mobile获取用户", notes = "传入用户手机号")
    @GetMapping("/loadUserByMobile")
    public Result<UserDto> loadUserByMobile(String mobile) {

        User user = userService.loadUserByMobile(mobile);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        UserDto dto = new UserDto();
        BeanUtils.copyProperties(user, dto);
        dto.setResource(resourceAPIService.queryResourceByUserId(dto.getId()).stream().map(ResourceAPI::toVo).collect(Collectors.toSet()));
        return Result.success(dto);
    }








}
